<script setup>
import { queryPageApi, addApi, queryInfoApi, updateApi, deleteApi, handleViolationApi } from '@/api/std';
import { queryAllClazzsApi } from '@/api/clazz';
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'

// 学历选项
const degrees = ref([
  { label: '初中', value: 1 },
  { label: '高中', value: 2 },
  { label: '大专', value: 3 },
  { label: '本科', value: 4 },
  { label: '硕士', value: 5 },
  { label: '博士', value: 6 }
]);

// 性别选项
const genders = ref([
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]);

// 是否院校学员选项
const isCollegeOptions = ref([
  { label: '是', value: 1 },
  { label: '否', value: 0 }
]);

// 班级列表
const clazzs = ref([]);

// 搜索表单数据
const searchForm = ref({
  name: '',
  degree: '',
  clazzId: ''
});

// 查询所有班级
const loadAllClazzs = async () => {
  const result = await queryAllClazzsApi();
  if (result.code) {
    clazzs.value = result.data;
  }
};

// 查询方法
const search = async () => {
  // 根据API请求健壮性规范，避免将空值参数传递给后端
  const params = {};
  if (searchForm.value.name) params.name = searchForm.value.name;
  if (searchForm.value.degree || searchForm.value.degree === 0) params.degree = searchForm.value.degree;
  if (searchForm.value.clazzId) params.clazzId = searchForm.value.clazzId;
  
  const result = await queryPageApi(
    params.name,
    params.degree,
    params.clazzId,
    currentPage.value,
    pageSize.value
  );
  if (result.code) {
    stuList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 清空方法
const clear = () => {
  searchForm.value = {
    name: '',
    degree: '',
    clazzId: ''
  };
  search();
};

// 学员列表数据
const stuList = ref([]);

// 分页
const currentPage = ref(1); //页码
const pageSize = ref(10); //每页展示记录数
const background = ref(true); //背景色
const total = ref(0); //总记录数

// 组件挂载时加载班级数据
onMounted(() => {
  loadAllClazzs();
  loadStuData();
});

// 加载学员数据
const loadStuData = async () => {
  // 根据API请求健壮性规范，避免将空值参数传递给后端
  const params = {};
  if (searchForm.value.name) params.name = searchForm.value.name;
  if (searchForm.value.degree || searchForm.value.degree === 0) params.degree = searchForm.value.degree;
  if (searchForm.value.clazzId) params.clazzId = searchForm.value.clazzId;
  
  const result = await queryPageApi(
    params.name,
    params.degree,
    params.clazzId,
    currentPage.value,
    pageSize.value
  );
  if (result.code) {
    stuList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 每页展示记录数变化
const handleSizeChange = () => {
  loadStuData();
};

// 页码变化时触发
const handleCurrentChange = () => {
  loadStuData();
};

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增学员')

// 学员表单数据
const student = ref({
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''
})

// 表单引用
const stuFormRef = ref();

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { len: 10, message: '学号长度应为10个字符', trigger: 'blur' },
    // 在编辑模式下，如果已有学号则不强制重新输入，但若修改了则必须符合规则
    { 
      validator: (rule, value, callback) => {
        if (student.value.id && !value) {
          callback(new Error('学号不能为空'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { len: 18, message: '身份证号长度应为18位', trigger: 'blur' }
  ],
  isCollege: [
    { required: true, message: '请选择是否为院校学员', trigger: 'change' }
  ],
  degree: [
    { required: true, message: '请选择最高学历', trigger: 'change' }
  ],
  graduationDate: [
    { required: true, message: '请选择毕业时间', trigger: 'change' }
  ],
  clazzId: [
    { required: true, message: '请选择所属班级', trigger: 'change' }
  ]
});

// 新增学员
const addStudent = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增学员';
  student.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  }

  // 重置表单的校验规则-提示信息
  if (stuFormRef.value) {
    stuFormRef.value.resetFields();
  }
}

// 编辑学员
const editStudent = async (id) => {
  const result = await queryInfoApi(id);
  if (result.code) {
    dialogVisible.value = true;
    dialogTitle.value = '修改学员';
    student.value = result.data;
  }
}

// 保存学员
const save = async () => {
  // 表单校验
  if (!stuFormRef.value) return;
  stuFormRef.value.validate(async (valid) => {
    if (valid) {
      let result;
      if (student.value.id) { // 修改
        result = await updateApi(student.value);
      } else { // 新增
        result = await addApi(student.value);
      }

      if (result.code) {
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        loadStuData();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      ElMessage.error('表单校验不通过');
    }
  })
}

// 删除学员
const deleteStudent = (id) => {
  ElMessageBox.confirm('您确定要删除该学员吗？', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 修改为通过URL参数传递id
    const result = await deleteApi(id);
    if (result.code) {
      ElMessage.success('删除成功');
      loadStuData();
    } else {
      ElMessage.error(result.msg);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 批量删除学员
const selectedStuIds = ref([]);
const handleSelectionChange = (selection) => {
  selectedStuIds.value = selection.map(item => item.id);
}

const deleteStudents = () => {
  if (selectedStuIds.value.length === 0) {
    ElMessage.warning('请至少选择一个学员');
    return;
  }
  
  ElMessageBox.confirm(`您确定要删除这 ${selectedStuIds.value.length} 个学员吗？`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 修改为逐个删除，因为接口只支持单个删除
    const deletePromises = selectedStuIds.value.map(id => deleteApi(id));
    try {
      const results = await Promise.all(deletePromises);
      // 检查所有删除操作是否都成功
      const allSuccess = results.every(result => result.code);
      if (allSuccess) {
        ElMessage.success('删除成功');
        loadStuData();
      } else {
        ElMessage.error('部分删除失败');
      }
    } catch (error) {
      ElMessage.error('删除过程中出现错误');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 违纪处理相关
const violationDialogVisible = ref(false)
const violationForm = ref({
  id: '',
  violationScore: ''
})
const violationFormRef = ref()

// 违纪处理表单校验规则
const violationRules = ref({
  violationScore: [
    { required: true, message: '请输入违纪扣分', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
  ]
})

// 处理违纪
const handleViolation = (id) => {
  violationForm.value.id = id
  violationForm.value.violationScore = ''
  violationDialogVisible.value = true
  
  // 重置表单校验
  if (violationFormRef.value) {
    violationFormRef.value.resetFields()
  }
}

// 保存违纪信息
const saveViolation = async () => {
  if (!violationFormRef.value) return
  violationFormRef.value.validate(async (valid) => {
    if (valid) {
      // 修改：传递正确的参数格式，包括学员ID和违纪分数
      const result = await handleViolationApi(violationForm.value.id, violationForm.value.violationScore)
      if (result.code) {
        ElMessage.success('违纪处理成功')
        violationDialogVisible.value = false
        loadStuData()
      } else {
        ElMessage.error(result.msg)
      }
    } else {
      ElMessage.error('表单校验不通过')
    }
  })
}

</script>

<template>
  <div class="container">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchForm.name" placeholder="请输入学员姓名" />
      </el-form-item>

      <el-form-item label="最高学历">
        <el-select v-model="searchForm.degree" placeholder="请选择">
          <el-option
            v-for="item in degrees"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属班级">
        <el-select v-model="searchForm.clazzId" placeholder="请选择">
          <el-option
            v-for="item in clazzs"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  
  <!-- 功能按钮 -->
  <div class="container">
    <el-button type="primary" @click="addStudent">+ 新增学员</el-button>
    <el-button type="danger" @click="deleteStudents">- 批量删除</el-button>
  </div>

  <!-- 数据展示表格 -->
  <div class="container">
    <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="name" label="姓名" width="120" align="center"/>
      <el-table-column prop="no" label="学号" width="120" align="center"/>
      <el-table-column prop="clazzName" label="班级" width="120" align="center"/>
      <el-table-column label="性别" width="80" align="center">
        <template #default="scope">
          {{ scope.row.gender == 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="120" align="center"/>
      <el-table-column label="最高学历" width="100" align="center">
        <template #default="scope">
          <span v-if="scope.row.degree >= 1 && scope.row.degree <= 6">
            {{ degrees[scope.row.degree - 1].label }}
          </span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="violationCount" label="违纪次数" width="100" align="center"/>
      <el-table-column prop="violationScore" label="违纪扣分" width="100" align="center"/>
      <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editStudent(scope.row.id)"><el-icon><EditPen /></el-icon> 编辑</el-button>
          <el-button type="warning" size="small" @click="handleViolation(scope.row.id)"><el-icon><Warning /></el-icon> 违纪</el-button>
          <el-button type="danger" size="small" @click="deleteStudent(scope.row.id)"><el-icon><Delete /></el-icon> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <div class="container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 50, 75, 100]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  
  <!-- 新增/修改学员的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <el-form :model="student" :rules="rules" ref="stuFormRef" label-width="100px">
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="student.name" placeholder="请输入姓名，2-10个字"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="student.no" placeholder="请输入学号，10个字"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="student.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option
                v-for="item in genders"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="student.phone" placeholder="请输入员工手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证" prop="idCard">
            <el-input v-model="student.idCard" placeholder="请输入身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校学员" prop="isCollege">
            <el-select v-model="student.isCollege" placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="item in isCollegeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="student.address" placeholder="请输入联系地址，最多100字"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历" prop="degree">
            <el-select v-model="student.degree" placeholder="请选择最高学历" style="width: 100%;">
              <el-option
                v-for="item in degrees"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间" prop="graduationDate">
            <el-date-picker
              v-model="student.graduationDate"
              type="date"
              placeholder="请选择毕业时间"
              style="width: 100%;"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" prop="clazzId">
            <el-select v-model="student.clazzId" placeholder="请选择所属班级" style="width: 100%;">
              <el-option
                v-for="item in clazzs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 学员违纪处理弹窗 -->
  <el-dialog v-model="violationDialogVisible" title="学员违纪处理" width="400px">
    <el-form :model="violationForm" :rules="violationRules" ref="violationFormRef" label-width="80px">
      <el-form-item label="违纪扣分" prop="violationScore">
        <el-input v-model="violationForm.violationScore" placeholder="请输入违纪扣分"></el-input>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="violationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveViolation">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.container {
  margin: 10px 0px;
}
</style>